package com.ptmall.app.ui.fragment;

import android.animation.Animator;
import android.animation.ValueAnimator;
import android.content.Intent;
import android.graphics.Path;
import android.graphics.PathMeasure;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ptmall.app.MainActivity;
import com.ptmall.app.R;
import com.ptmall.app.base.BaseMvpFragment;
import com.ptmall.app.bean.PageData;
import com.ptmall.app.bean.ProductBean;
import com.ptmall.app.bean.ShopCarBean;
import com.ptmall.app.net.api.ApiDataRepository;
import com.ptmall.app.net.base.ApiNetResponse;
import com.ptmall.app.ui.activity.ConfirmOrderActivity;
import com.ptmall.app.ui.activity.CoudanActivity;
import com.ptmall.app.ui.adapter.LikeGoodAdapter;
import com.ptmall.app.ui.adapter.ShopCarAdapter;
import com.ptmall.app.view.NoScrollGridView;
import com.ptmall.app.view.NoScrollListView;
import com.ptmall.app.view.PullToRefreshLayout;
import com.ptmall.app.view.TitleBarView;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.ptmall.app.MainActivity.MANJIAN;


public class ShopCarfragment extends BaseMvpFragment implements View.OnClickListener {

    View view, datanull, likeview;
    TitleBarView titlebar;

    NoScrollListView shopcarlist;
    NoScrollGridView likelist;
    ApiDataRepository apiDataRepository = ApiDataRepository.getInstance();
    LikeGoodAdapter mLikeGoodAdapter;
    ShopCarAdapter mShopCarAdapter;

    RelativeLayout tocoudan;
    TextView allprice_text, confirm_text,desc;
    ImageView all_selected_img;
    String allprice;
    int select_num = 0;

    //是否全选标签
    private boolean mSelect;
    List<ShopCarBean> shopCarBeanList = new ArrayList<>();
    List<ShopCarBean> confrimList = new ArrayList<>();

    RelativeLayout rl;
    private PathMeasure mPathMeasure;
    private float[] mCurrentPosition = new float[2];

    boolean isEditing;
    Button qgg;


    private PullToRefreshLayout ptrl;
    int page = 1;
    List<ProductBean> likeArraylist = new ArrayList<>();

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_shopcar, container, false);

        return view;
    }

    @Override
    public void initViews() {
        ptrl = (PullToRefreshLayout) view.findViewById(R.id.refresh_view);
        all_selected_img = (ImageView) view.findViewById(R.id.all_select);
        confirm_text = (TextView) view.findViewById(R.id.confirm);
        likeview = view.findViewById(R.id.likeview);
        datanull = view.findViewById(R.id.datanull);
        allprice_text = (TextView) view.findViewById(R.id.allprice);
        tocoudan = (RelativeLayout) view.findViewById(R.id.tocoudan);
        desc = (TextView) view.findViewById(R.id.desc);
        shopcarlist = (NoScrollListView) view.findViewById(R.id.shopcarlist);
        rl = (RelativeLayout) view.findViewById(R.id.rl);
        likelist = (NoScrollGridView) likeview.findViewById(R.id.likelist);
        titlebar = (TitleBarView) view.findViewById(R.id.titlebar);
        qgg = (Button) view.findViewById(R.id.qgg);
        titlebar.setOnTitleBarClickListener(new TitleBarView.TitleBarClickListener() {
            @Override
            public void leftClick() {

            }

            @Override
            public void rightClick() {
                if (isEditing) {
                    isEditing = false;
                    for (ShopCarBean shopCarBean : shopCarBeanList) {
                        shopCarBean.selected = false;
                    }
                    mShopCarAdapter.pushData(shopCarBeanList);
                    titlebar.setRightText("编辑");
                    getData();
                } else {

                    isEditing = true;
                    for (ShopCarBean shopCarBean : shopCarBeanList) {
                        shopCarBean.selected = false;
                    }
                    mShopCarAdapter.pushData(shopCarBeanList);
                    titlebar.setRightText("完成");
                    confirm_text.setText("删除");
                }
            }
        });
        tocoudan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getContext(),CoudanActivity.class);
                intent.putExtra("desc",desc.getText().toString());
                startActivity(intent);

            }
        });
        qgg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ((MainActivity)getActivity()).mVpMain.setCurrentItem(0);
            }
        });
        titlebar.setLeftBtnVisable(false);
        confirm_text.setOnClickListener(this);

        mLikeGoodAdapter = new LikeGoodAdapter(getContext(), likeArraylist);
        likelist.setAdapter(mLikeGoodAdapter);
        mLikeGoodAdapter.setClickInterface(new LikeGoodAdapter.ClickInterface() {
            @Override
            public void shopcaradd(ImageView iv,int position, String id) {
                addcar(id, "1",iv);
            }
        });
        getlike();

        ptrl.setOnRefreshListener(new PullToRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
                page = 1;
                getlike();

            }

            @Override
            public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {
                page ++;
                getlike();
            }
        });


    }

    private void getlike(){
        Map<String,String> map = new HashMap<>();
        map.put("page",page+"");
        apiDataRepository.cnxh(map, new ApiNetResponse<PageData<ProductBean>>() {
            @Override
            public void onSuccess(PageData<ProductBean> data) {

                if (null != ptrl) {
                    ptrl.refreshFinish(PullToRefreshLayout.SUCCEED);
                    ptrl.loadmoreFinish(PullToRefreshLayout.SUCCEED);
                }
                if (page == 1) {
                    likeArraylist.clear();
                }
                if (null != data.getData() && data.getData().size() > 0) {
                    likeArraylist.addAll(data.getData());
                } else {
                }
                mLikeGoodAdapter.pushData(likeArraylist);

            }
        });
    }

    @Override
    public void initEvents() {
        mLikeGoodAdapter = new LikeGoodAdapter(getContext(), null);
        likelist.setAdapter(mLikeGoodAdapter);
        mShopCarAdapter = new ShopCarAdapter(getContext(), shopCarBeanList);
        shopcarlist.setAdapter(mShopCarAdapter);
        mLikeGoodAdapter.setClickInterface(new LikeGoodAdapter.ClickInterface() {
            @Override
            public void shopcaradd(ImageView iv, int position, String id) {
                addcar(id, "1",iv);
            }

        });

        mShopCarAdapter.setClickInterface(new ShopCarAdapter.ClickInterface() {
            @Override
            public void chechClick(String id, int position) {
                shopCarBeanList.get(position).selected = !shopCarBeanList.get(position).selected;
                mShopCarAdapter.pushData(shopCarBeanList);
            }

            @Override
            public void isAllCheck(boolean selected) {
                mSelect = selected;
                if (selected) {
                    all_selected_img.setImageResource(R.drawable.shopcar_true);
                } else {
                    all_selected_img.setImageResource(R.drawable.shopcar_unselected);
                }

            }

            @Override
            public void goodprice() {
                totalPrice();
            }

            @Override
            public void shopcaradd(int position) {
                if(shopCarBeanList.get(position).num.equals("1")){
                    showMsg("不能在少啦！");
                    return;
                }
//                shopCarBeanList.get(position).num = ((Integer.parseInt(shopCarBeanList.get(position).num) + 1) + "");
                shopcaraddmu(shopCarBeanList.get(position).cartId, "2");
            }

            @Override
            public void shopcarjian(int position) {

//                shopCarBeanList.get(position).num = ((Integer.parseInt(shopCarBeanList.get(position).num) - 1) + "");
                shopcaraddmu(shopCarBeanList.get(position).cartId, "1");
            }
        });

        mLikeGoodAdapter.setClickInterface(new LikeGoodAdapter.ClickInterface() {
            @Override
            public void shopcaradd(ImageView iv, int position, String id) {
                addcar(id,iv);
            }

        });

        all_selected_img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mSelect) {
                    for (ShopCarBean shopCarBean : shopCarBeanList) {
                        shopCarBean.selected = false;
                    }
                } else {
                    for (ShopCarBean shopCarBean : shopCarBeanList) {
                        shopCarBean.selected = true;
                    }
                }
                mShopCarAdapter.pushData(shopCarBeanList);
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        getData();
    }

    public void getData() {
        apiDataRepository.getShopCarList(null, new ApiNetResponse<PageData<ShopCarBean>>() {
            @Override
            public void onSuccess(PageData<ShopCarBean> data) {
                shopCarBeanList.clear();
                shopCarBeanList.addAll(data.getData());
//                mLikeGoodAdapter.pushData(data.like);
                if (data.getData().size() > 0) {
                    mShopCarAdapter.pushData(shopCarBeanList);
                    datanull.setVisibility(View.GONE);
                } else {
                    mShopCarAdapter.pushData(shopCarBeanList);
                    datanull.setVisibility(View.VISIBLE);
                }
                ((MainActivity)getActivity()).mBadgeView.setText(shopCarBeanList.size()+"");
                totalPrice();
            }
        });
    }

    private void totalPrice() {

        allprice = "0";
        select_num = 0;

        for (int i = 0; i < shopCarBeanList.size(); i++) {
            if (shopCarBeanList.get(i).selected) {
                try {

                    allprice = new BigDecimal(allprice).add(new BigDecimal(shopCarBeanList.get(i).num)
                            .multiply(new BigDecimal(shopCarBeanList.get(i).sell_price)).setScale(2))
                            .setScale(2).toEngineeringString();

                    if(new BigDecimal(shopCarBeanList.get(i).num)
                            .multiply(new BigDecimal(shopCarBeanList.get(i).sell_price)).doubleValue()
                            >=new BigDecimal(shopCarBeanList.get(i).man).doubleValue()){
                        allprice = new BigDecimal(allprice)
                                .subtract(new BigDecimal(shopCarBeanList.get(i).jian)).setScale(2).toPlainString();
                    }


                    select_num++;
                } catch (Exception e) {

                }
            }
        }
        if (!isEditing) {
            confirm_text.setText("结算（" + select_num + "）");
        }
        if(new BigDecimal(MANJIAN).doubleValue()<new BigDecimal(allprice).doubleValue()){
            desc.setText("已满"+ MANJIAN+",可减运费");
            tocoudan.setVisibility(View.GONE);
        }else {
            desc.setText("满"+ MANJIAN+"可减运费，还差"+new BigDecimal(MANJIAN).setScale(2).subtract(new BigDecimal(allprice)).setScale(2).toPlainString()+"元");
            tocoudan.setVisibility(View.VISIBLE);
        }
        allprice_text.setText("￥" + allprice);
    }

    private String getdelshopcarlist() {
        StringBuffer delshopcarids = new StringBuffer();
        for (int i = 0; i < shopCarBeanList.size(); i++) {
            if (shopCarBeanList.get(i).selected) {
                delshopcarids.append(shopCarBeanList.get(i).cartId + ",");
            }
        }
        if (delshopcarids.equals("")) {
            return "";
        }
        if(TextUtils.isEmpty(delshopcarids)){
            showMsg("请选择商品");
            return "";
        }
        delshopcarids.deleteCharAt(delshopcarids.length() - 1);
        return delshopcarids.toString();
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.confirm:
                if (isEditing) {
                    delshopcargood();
                } else {
                    //提交
//                    showMsg("提交");
                    if(new BigDecimal(allprice).doubleValue()<new BigDecimal(MainActivity.QISONG).doubleValue()){
                        showMsg("满"+MainActivity.QISONG+"起送");
                        return;
                    }
                    confrimList.clear();
                    for (ShopCarBean shopCarBean : shopCarBeanList) {
                        if (shopCarBean.selected) {
                            confrimList.add(shopCarBean);
                        }
                    }
                    if (confrimList.size() == 0) {
                        showMsg("请选择结算商品");
                        return;
                    }
                    Intent intent = new Intent(getContext(), ConfirmOrderActivity.class);
                    intent.putExtra("list", (Serializable) confrimList);
                    startActivity(intent);
                }
                break;
        }
    }

    private void shopcaraddmu(String cartId, String type) {
        Map<String, String> map = new HashMap<>();
        map.put("cartId", cartId);
        map.put("type", type);
        apiDataRepository.shopCarAdd(map, new ApiNetResponse<Object>(getContext()) {
            @Override
            public void onSuccess(Object data) {
                getData();
            }
        });
    }


    private void delshopcargood() {
        Map<String, String> map = new HashMap<>();
        if(TextUtils.isEmpty(getdelshopcarlist().toString())){
            return;
        }
        map.put("cartIds", getdelshopcarlist().toString());
        apiDataRepository.delShopCarGood(map, new ApiNetResponse<Object>(getContext()) {
            @Override
            public void onSuccess(Object data) {
                getData();
            }
        });
    }

    private void addcar(String id,ImageView iv) {
        Map<String, String> map = new HashMap<>();
        map.put("productId", id);
        map.put("num", "1");
        apiDataRepository.addShopCar(map, new ApiNetResponse<Object>(getContext()) {
            @Override
            public void onSuccess(Object data) {
                showMsg("加入购物车成功");
                getData();
                addCartStart(iv);
            }
        });
    }


    private void addcar(String id, String num,ImageView iv) {
        Map<String, String> map = new HashMap<>();
        map.put("productId", id);
        map.put("num", num);
        apiDataRepository.addShopCar(map, new ApiNetResponse<Object>() {
            @Override
            public void onSuccess(Object data) {
                showMsg("加入购物车成功");
                addCartStart(iv);

            }
        });
    }
    /**
     * ★★★★★把商品添加到购物车的动画效果★★★★★
     * @param iv
     */
    private void addCartStart( ImageView iv) {
//      一、创造出执行动画的主题---imageview
        //代码new一个imageview，图片资源是上面的imageview的图片
        // (这个图片就是执行动画的图片，从开始位置出发，经过一个抛物线（贝塞尔曲线），移动到购物车里)
        final ImageView goods = new ImageView(getContext());
        goods.setImageDrawable(iv.getDrawable());
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(100, 100);
        rl.addView(goods, params);

//        二、计算动画开始/结束点的坐标的准备工作
        //得到父布局的起始点坐标（用于辅助计算动画开始/结束时的点的坐标）
        int[] parentLocation = new int[2];
        rl.getLocationInWindow(parentLocation);

        //得到商品图片的坐标（用于计算动画开始的坐标）
        int startLoc[] = new int[2];
        iv.getLocationInWindow(startLoc);

        //得到购物车图片的坐标(用于计算动画结束后的坐标)
        int endLoc[] = new int[2];
        endLoc[0] = rl.getWidth()/8*4;
        endLoc[1] = rl.getHeight()-50;
//        car.getLocationInWindow(endLoc);


//        三、正式开始计算动画开始/结束的坐标
        //开始掉落的商品的起始点：商品起始点-父布局起始点+该商品图片的一半
        float startX = startLoc[0] - parentLocation[0] + iv.getWidth() / 2;
        float startY = startLoc[1] - parentLocation[1] + iv.getHeight() / 2;

        //商品掉落后的终点坐标：购物车起始点-父布局起始点+购物车图片的1/5
        float toX = endLoc[0] - parentLocation[0];
        float toY = endLoc[1] - parentLocation[1];
        Log.i("location ====","endLoc[]" + endLoc[0] + "  " + endLoc[1]);
        Log.i("location ====","toX[]" + toX + " toY " + toY);
//        四、计算中间动画的插值坐标（贝塞尔曲线）（其实就是用贝塞尔曲线来完成起终点的过程）
        //开始绘制贝塞尔曲线
        Path path = new Path();
        //移动到起始点（贝塞尔曲线的起点）
        path.moveTo(startX, startY);
        //使用二次萨贝尔曲线：注意第一个起始坐标越大，贝塞尔曲线的横向距离就会越大，一般按照下面的式子取即可
        path.quadTo((startX + toX) / 2, startY, toX, toY);
        //mPathMeasure用来计算贝塞尔曲线的曲线长度和贝塞尔曲线中间插值的坐标，
        // 如果是true，path会形成一个闭环
        mPathMeasure = new PathMeasure(path, false);

        //★★★属性动画实现（从0到贝塞尔曲线的长度之间进行插值计算，获取中间过程的距离值）
        ValueAnimator valueAnimator = ValueAnimator.ofFloat(0, mPathMeasure.getLength());
        valueAnimator.setDuration(500);
        // 匀速线性插值器
        valueAnimator.setInterpolator(new LinearInterpolator());
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                // 当插值计算进行时，获取中间的每个值，
                // 这里这个值是中间过程中的曲线长度（下面根据这个值来得出中间点的坐标值）
                float value = (Float) animation.getAnimatedValue();
                // ★★★★★获取当前点坐标封装到mCurrentPosition
                // boolean getPosTan(float distance, float[] pos, float[] tan) ：
                // 传入一个距离distance(0<=distance<=getLength())，然后会计算当前距
                // 离的坐标点和切线，pos会自动填充上坐标，这个方法很重要。
                mPathMeasure.getPosTan(value, mCurrentPosition, null);//mCurrentPosition此时就是中间距离点的坐标值
                // 移动的商品图片（动画图片）的坐标设置为该中间点的坐标
                goods.setTranslationX(mCurrentPosition[0]);
                goods.setTranslationY(mCurrentPosition[1]);
            }
        });
//      五、 开始执行动画
        valueAnimator.start();

//      六、动画结束后的处理
        valueAnimator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {

            }

            //当动画结束后：
            @Override
            public void onAnimationEnd(Animator animation) {
                rl.removeView(goods);
            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });
    }

}
